<template>
  <div>
    <!-- 查询区域 -->
    <el-card shadow="never" class="query-card">
      <el-form :model="queryParams" label-width="70px" :inline="true" ref="queryFormRef">
        <!-- 机构名称 -->
        <el-form-item label="机构名称" label-width="auto" prop="orgName">
          <el-input v-model="queryParams.orgName" class="!w-50" placeholder="请输入机构名称" clearable />
        </el-form-item>

        <!-- 机构类型 -->
        <el-form-item label="机构类型" label-width="auto" prop="orgType">
          <el-select v-model="queryParams.orgType" placeholder="全部" clearable style="width: 180px">
            <el-option v-for="item in organizationOptions" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 机构层级 -->
        <el-form-item label="机构层级" label-width="auto" prop="level">
          <el-select v-model="queryParams.level" placeholder="全部" clearable style="width: 180px">
            <el-option v-for="item in levelOptions" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 审核时间 -->
        <el-form-item label="审核时间" label-width="auto" prop="auditTime">
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="queryParams.auditTime" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px" />
        </el-form-item>

        <!-- 审核状态 -->
        <el-form-item label="审核状态" label-width="auto" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="全部" clearable style="width: 180px">
            <el-option :label="item.label" v-for="item in auditStatusOptions" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 180px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <!-- 经营所在区域 -->
        <!-- <el-form-item label="经营所在区域" prop="region">
          <el-cascader v-model="queryParams.region" :options="regionOptions" placeholder="请选择" clearable
            style="width: 220px" />
        </el-form-item> -->

        <!-- 查询和重置 -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div>
      <el-button type="primary" @click="handleAdd">
        新 增
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table class="mt-5" :data="organizationList" border style="width: 100%" header-cell-class-name="table-header">
      <!-- 机构名称 -->
      <el-table-column prop="orgName" label="机构名称" width="180" show-overflow-tooltip align="center">
      </el-table-column>

      <!-- Logo -->
      <el-table-column label="logo" width="140" align="center">
        <template #default="{ row }">
          <el-image v-if="row.logo" :src="row.logo" fit="contain"
            style="width: 100px; height: 36px; border-radius: 4px" />
          <span v-else>--</span>
        </template>
      </el-table-column>

      <!-- 机构类型 -->
      <el-table-column prop="orgType" label="机构类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag size="small" type="info">{{ transformDict('organizationType', row.orgType) }}</el-tag>
        </template>
      </el-table-column>

      <!-- 所在省份 -->
      <el-table-column prop="province" label="所在省份" width="100" align="center" />

      <!-- 城市 -->
      <el-table-column prop="city" label="城市" width="80" align="center" />

      <!-- 所在区县 -->
      <el-table-column prop="district" label="所在区县" width="100" align="center" />

      <!-- 机构层级 -->
      <el-table-column prop="level" label="机构层级" width="100" align="center">
        <template #default="{ row }">
          {{ transformDict('organizationLevel', row.level) }}
        </template>
      </el-table-column>

      <!-- 推荐 -->
      <el-table-column label="推荐" width="70" prop="recommend" align="center">
        <template #default="{ row }">
          <el-tag :type="row.recommend == 0 ? 'danger' : 'success'" size="small">{{ row.recommend == 0 ? '否' : '是'
            }}</el-tag>
        </template>
      </el-table-column>

      <!-- 置顶 -->
      <el-table-column label="置顶" width="70" prop="top" align="center">
      </el-table-column>

      <!-- 状态 -->
      <el-table-column label="状态" width="70" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
            {{ row.status === 'enabled' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 审核状态 -->
      <!-- <el-table-column label="审核状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusType(row.auditStatus)" size="small">
              {{ getAuditStatusLabel(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column> -->

      <!-- 拒绝原因 -->
      <el-table-column label="拒绝原因" width="100" align="center">
        <template #default="{ row }">
          <el-popover v-if="row.auditStatus === 'rejected' && row.rejectReason" placement="top" width="220"
            trigger="hover" :content="row.rejectReason">
            <template #reference>
              <el-button link type="danger" size="small">查看</el-button>
            </template>
          </el-popover>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <!-- 审核时间 -->
      <el-table-column prop="auditTime" label="审核时间" width="150" align="center" />

      <!-- 操作 -->
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="success" @click="handleView(row)">详情</el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（可选） -->
    <div class="pagination" style="margin-top: 20px; text-align: right">
      <el-pagination background v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :total="total" layout="total, prev, pager, next" @current-change="handleData" />
    </div>

    <!-- Institution Dialog -->
    <el-dialog v-model="dialogVisible" title="机构信息" width="800px">
      <el-form :disabled="disabled" class="pr-4" ref="formRef" :model="formData" label-width="100px">
        <!-- Organization Name -->
        <el-form-item label="机构名称" prop="orgName" :rules="{ required: true, message: '请输入机构名称', trigger: 'blur' }">
          <el-input size="large" v-model="formData.orgName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item class="!flex-items-start" label="机构简称" prop="shortName"
          :rules="{ required: true, message: '请输入机构简称', trigger: 'blur' }">
          <el-input size="large" type="textarea" v-model="formData.shortName" placeholder="请输入机构简称" />
        </el-form-item>
        <el-form-item label="机构介绍" prop="introduction" :rules="{ required: true, message: '请输入机构介绍', trigger: 'blur' }">
          <el-input size="large" v-model="formData.introduction" placeholder="请输入机构介绍" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address" :rules="{ required: true, message: '请输入详细地址', trigger: 'blur' }">
          <el-input size="large" v-model="formData.address" placeholder="请输入详细地址" />
        </el-form-item>

        <!-- Logo -->
        <el-form-item label="Logo" class="!flex-items-start"
          :rules="{ required: true, message: '请上传Logo', trigger: 'change' }">
          <OneUpload v-model="formData.logo"></OneUpload>
        </el-form-item>
        <el-form-item label="推荐Logo" class="!flex-items-start"
          :rules="{ required: true, message: '请上传推荐Logo', trigger: 'change' }">
          <OneUpload v-model="formData.recommendLogo"></OneUpload>
        </el-form-item>

        <!-- Organization Type -->
        <el-form-item label="机构类型" prop="orgType" :rules="{ required: true, message: '请选择机构类型', trigger: 'change' }">
          <el-select size="large" v-model="formData.orgType" placeholder="请选择机构类型">
            <el-option v-for="(item, index) in organizationOptions" :key="index" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.parentId !== 0" label="上级机构" prop="parentId"
          :rules="{ required: true, message: '请选择上级机构', trigger: 'change' }">
          <el-select size="large" v-model="formData.parentId" placeholder="请选择上级机构">
            <el-option v-for="(item, index) in organizationList" :key="index" :label="item.orgName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用区域" prop="national" :rules="{ required: true, message: '请选择适用区域', trigger: 'change' }">
          <el-radio-group v-model="national" @change="handleNational">
            <el-radio value="all">全国</el-radio>
            <el-radio value="area">选择区域</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="national == 'area'" label="覆盖范围" prop="national"
          :rules="{ required: true, message: '请选择覆盖范围', trigger: 'change' }">
          <el-input class="w-9/10" type="text" readonly size="large" v-model="formData.national">
            <template #append>
              <el-button @click="areaVisbled = true" type="primary">选择区域</el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- Province -->
        <el-form-item label="所在省份" prop="province" :rules="{ required: true, message: '请选择所在省份', trigger: 'change' }">
          <CityChoose v-model:provinceSiteId="formData.provinceCode" @dataChange="regditArea"
            v-model:citySiteId="formData.cityCode" v-model:areaSiteId="formData.districtCode">
          </CityChoose>
        </el-form-item>

        <!-- Organization Level -->
        <!-- <el-form-item label="机构层级" prop="level">
        <el-select size="large" v-model="formData.level" placeholder="请选择机构层级">
          <el-option v-for="(item, index) in levelOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->


        <!-- Status -->
        <el-form-item label="状态" prop="status" :rules="{ required: true, message: '请选择状态', trigger: 'change' }">
          <el-switch v-model="formData.status" active-value="1" inactive-value="0" active-text="开启"
            inactive-text="关闭" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" v-if="!disabled" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <AreaChoose v-model="areaVisbled" @select="handleSelect"></AreaChoose>
  </div>
</template>

<script lang="ts" setup>

const dialogVisible = ref(false)
const areaVisbled = ref(false)
const national = ref('')

const formData = reactive({
  orgName: '',
  logo: '',
  orgType: '',
  province: '',
  parentId: "",
  city: '',
  district: '',
  recommendLogo: '',
  level: '',
  recommend: 0,
  introduction: '',
  top: 0,
  status: '1'
})

const formRef = ref();

const handleSelect = (nodes) => {
  formData.national = nodes.map(m => m.label).join(',')
  formData.nationalCode = nodes.map(m => m.regionCode).join(',')
  areaVisbled.value = false
}

function handleNational(v) {
  if (v == 'all') {
    formData.national = '全国'
    formData.nationalCode = v
  }
}

function regditArea(o) {
  formData.province = o.provinceName
  formData.city = o.cityName
  formData.district = o.areaName
}

const disabled = ref(false)
function handleView(row) {
  Object.assign(formData, row)
  dialogVisible.value = true
  disabled.value = true
}


function handleAdd() {
  dialogVisible.value = true
  disabled.value = false
  reset()
}

function reset() {

  formData.orgName = ''
  formData.logo = ''
  formData.national = ''
  formData.nationalCode = ''
  formData.provinceCode = ''
  formData.cityCode = ''
  formData.districtCode = ''
  formData.shortName = ''
  formData.address = ''
  formData.orgType = ''
  formData.province = ''
  formData.parentId = ''
  formData.city = ''
  formData.district = ''
  formData.recommendLogo = ''
  formData.level = ''
  formData.recommend = 0
  formData.introduction = ''
  formData.top = 0
  formData.status = '1'
  formData.id = ''
}

function handleEdit(row) {
  console.log('编辑机构:', row);

  disabled.value = false
  Object.assign(formData, row)
  formData.orgType = row.orgType.toString()
  // formData.level = row.level.toString()
  if (formData.nationalCode === 'all') {
    national.value = 'all'
  } else {
    national.value = 'area'
  }
  dialogVisible.value = true
}

const { organizationType: organizationOptions, organizationLevel: levelOptions, auditStatus: auditStatusOptions } = useDict('organizationType', 'organizationLevel', 'auditStatus')

// 查询参数
const queryParams = reactive({
  orgName: '',
  orgType: '',
  level: '',
  pageNum: 1,
  pageSize: 10,
  auditTime: [],
  auditStatus: '',
  status: '',
  region: []
})

onMounted(() => {
  // 初始化查询
  handleData()
})

const organizationList = ref([])
const total = ref(0)
const handleData = () => {
  manageOrganizations(queryParams).then(res => {
    console.log('机构列表:', res)
    // 处理返回数据
    organizationList.value = res.rows || []
    total.value = res.total || 0
  })
}

function submitForm() {
  formRef.value.validate().then((valid) => {
    if (valid) {
      if (formData.id) {
        updateInstitutionUdp(formData).then(res => {
          if (res.code == 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            handleData()
          }
        }).catch(err => {
          ElMessage.error(err.message)
        })
      } else {
        addInstitution(formData).then(res => {
          if (res.code == 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            handleData()
          }
        }).catch(err => {
          ElMessage.error(err.message)
        })
      }
    }
  })
}

// 表单引用
const queryFormRef = ref(null)



// 查询处理
const handleQuery = () => {
  console.log('查询条件:', { ...queryParams })
  handleData()
  // 调用 API 获取数据
}

// 重置处理
const handleReset = () => {
  queryFormRef.value?.resetFields()
  queryParams.auditTime = []
  queryParams.region = []
  // 可触发重新查询
  handleQuery()
}


import { manageOrganizations, addInstitution, updateInstitutionUdp } from '@/api/institution'
import AreaChoose from '@/components/areaChoose.vue'
import CityChoose from '@/components/cityChoose.vue'
import OneUpload from '@/components/oneUpload.vue'
import { useDict, transformDict } from '@/hooks/dict'
// 临时引入 ElMessage（实际项目中从 Element Plus 引入）
</script>

<style scoped lang="scss">
@use '@/assets/styles/el_form.scss';

.query-card {
  margin-bottom: 16px;
  border: none;
}

.table-card {
  border: none;
}

.table-header {
  background-color: #f8f8f8 !important;
  height: 60px;
  font-weight: bold;
}

.text-primary {
  color: #409eff;
  font-weight: 500;
}
</style>
